package top.infopub.mgr.hr.web;


import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import top.infopub.generic.GenericController;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.hr.domain.OrgInfoDomain;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.hr.service.WsStaffOfficeService;
import top.infopub.mgr.hr.vo.OrgInfoVo;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.mkt.PreProject;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.tdp.util.GrpParaUtil;

import com.github.pagehelper.Page;


/**
 * 公司管理
 * @author wangw
 * @version 2019年12月31日
 * @see OrgController
 * @since
 */
@Controller
@RequestMapping("/org")
public class OrgController extends GenericController {

    @Autowired
    private OrgInfoService orgInfoService;

    @Autowired
    private WsStaffOfficeService wsStaffOfficeService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    /**
     * 公司列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "hr/lay-orgInfo-list";
    }

    /**
     * 公司列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<OrgInfoDomain> queryDataByCondition(OrgInfoVo orgInfoVo, ParamPage paramPage) {
        Page<OrgInfoDomain> page = new Page<OrgInfoDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = orgInfoService.selectPageByDomainWhere(page, orgInfoVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 根据类型查找公司
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getOrgByTypes")
    @ResponseBody
    public Map<String, Object> getOrgByTypes(String types) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<OrgInfo> orgInfos = orgInfoService.selectByTypes(types);
            map.put("orgInfos", orgInfos);
        }
        catch (Exception e) {
            log.error("根据类型查找公司异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 根据类型查找公司
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getProjectById")
    @ResponseBody
    public Map<String, Object> getProjectById(String id) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            PreProject preProject = orgInfoService.selectProjectById(id);
            map.put("preProject", preProject);
        }
        catch (Exception e) {
            log.error("根据类型查找公司异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 新增/编辑公司
     * @param orgInfo
     * @return
     * @see
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/save")
    public @ResponseBody RspVo<OrgInfo> save(OrgInfo orgInfo) {
        if(StringUtils.isEmpty(orgInfo.getParentId())){
            orgInfo.setParentId("-1");
        }
        if (StringUtils.isEmpty(orgInfo.getCompName())
            || StringUtils.isEmpty(orgInfo.getTypes())){
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
        }
        // 新增
        if (StringUtils.isBlank(orgInfo.getId())) {
            //判断公司名称是否存在
            if (orgInfoService.selectByCompName(orgInfo.getCompName())) {
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("公司【"+orgInfo.getCompName()+"】已经存在~");
            }
        }else{
            //判断公司名称是否存在
            if (orgInfoService.selectByCompNameAndId(orgInfo.getCompName(),orgInfo.getId())) {
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("公司【"+orgInfo.getCompName()+"】已经存在~");
            }
        }
        orgInfoService.saveOrg(orgInfo);
        // 获得当前登录用户可见的所有公司与其子孙公司ids 不为空时存入session中
        String visibleOrgIds = wsStaffOfficeService.myAllVisibleOrg();
        if (!StringUtils.isBlank(visibleOrgIds)) {
            SessionUserUtils.setSessionAttribute("visibleOrgIds", visibleOrgIds);
        }
        if(StringUtils.isEmpty(orgInfo.getId())){
            LogUtil.bizLog(LogModelType.OTHER, AcctionType.ADD, "新增公司 - 公司名称:" + orgInfo.getCompName().trim(), null);
        }else{
            LogUtil.bizLog(LogModelType.OTHER, AcctionType.UPDATE, "修改公司 - 公司Id:" + orgInfo.getId(), null);
        }
        return RspVo.getSuccessResponse(orgInfo);
    }

    /**
     * 检查输入的公司名是否被占用(新增时使用)
     * @param compName 公司名
     * @return true 被占用, false 没有被占用
     */
    @RequestMapping(value = "/checkCompNameIsExist")
    @ResponseBody
    public boolean checkCompNameIsExist(String compName) {
        if (StringUtils.isBlank(compName)) return false;
        boolean flag = orgInfoService.selectByCompName(compName);
        return flag;
    }

    /**
     * 检查输入的公司名是否被占用(编辑时使用)
     * @param compName 手机号
     * @param id 当前被修改的公司Id
     * @return true 被占用, false 没有被占用
     */
    @RequestMapping(value = "/checkNewCompNameIsExist")
    @ResponseBody
    public boolean checkNewCompNameIsExist(String compName, String id) {
        if (StringUtils.isBlank(compName)) return false;
        boolean flag = orgInfoService.selectByCompNameAndId(compName, id);
        return flag;
    }
    /**
     * 修改公司状态
     * @param operatorVo
     * @return
     * @see
     */
    @RequestMapping("/updateStatus")
    public @ResponseBody RspVo<String> updateStatus(OrgInfo orgInfo) {
        OrgInfo org = orgInfoService.selectByPrimaryKey(orgInfo.getId());
        Integer oldStatus = org.getState();
        Integer newStatus = 0;
        if(oldStatus == 0){
            newStatus = 1;
        }else{
            newStatus = 0;
        }
        org.setState(newStatus);
        org.setUptTime(new Date());
        org.setUptBy(SessionUserUtils.getSessionUserId());
        orgInfoService.updateBySelective(org);
        // 操作日志
        LogUtil.bizLog(
            LogUtil.LogModelType.OTHER,
            LogUtil.AcctionType.UPDATE,
            "修改状态  公司名称:" + org.getCompName() + " 原状态:"
                + GrpParaUtil.getName("A00010020", String.valueOf(oldStatus)) + " 被修改为:"
                + GrpParaUtil.getName("A00010020", String.valueOf(newStatus)), "");
        return RspVo.getSuccessResponse();
    }

}
